<template>
    <div>
        <el-form
            class="filters searchForm"
            ref="searchForm"
            :model="searchForm"
            label-width="78px"
            size="mini"
        >
            <el-form-item label="设备编码" style="width: 22%">
                <el-input
                    type="textarea"
                    :rows="2"
                    :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：CC08DPC0202204250001\n0000092011500063'"
                    v-model="searchForm.codes"
                    @change.native="keyUp($event)"
                    @input.native="keyInput($event)"
                >
                </el-input>
            </el-form-item>
            <div class="search-btns detail-search-btns">
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doUpdateSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetDialogSearch"
                    >重置</el-button
                >
            </div>
        </el-form>

        <el-row :gutter="10">
            <el-col :span="18">
                <el-link class="link-text" :underline="false" type="danger"
                    >注：设备编码为红色文字的代表当前设备不可用</el-link
                >
                <el-link class="link-text" type="success" :underline="false"
                    >（已选择({{ unselectData.length }})个）</el-link
                >
                <Table
                    :height="isFullscreen ? '72vh' : '50vh'"
                    :tableHeader="equipTableHeader"
                    :tableData="equipTableData"
                    :tableLoading="handleListLoading"
                    :unselectData="unselectData"
                    @handleUnselectData="handleUnselectData"
                >
                    <template slot="codes" slot-scope="scope">
                        <div class="codes">
                            <span
                                :class="{
                                    isAllow: !scope.row.isAllowOperate,
                                }"
                                >{{ scope.row.code }}</span
                            >
                            <img
                                v-if="scope.row.isOnline == 1"
                                src="@/assets/image/online.png"
                                alt=""
                            />
                            <img
                                v-else
                                src="@/assets/image/offline.png"
                                alt=""
                            />
                        </div>
                    </template>
                    <template slot="softVersion" slot-scope="scope">
                        <span
                            style="text-align: left"
                            v-html="$options.filters.filterVersion(scope.row)"
                        ></span>
                    </template>
                </Table>

                <pagination
                    v-if="equipTotal > 0"
                    :total="equipTotal"
                    :page.sync="searchForm.pageNum"
                    :limit.sync="searchForm.pageSize"
                    @pagination="getDetailList"
                />
            </el-col>
            <el-col :span="6">
                <el-link class="link-text" :underline="false" type="danger"
                    >关联的设备列表</el-link
                >
                <Table
                    style="width: 100%"
                    :tableHeader="unselectTableHeader"
                    :tableData="unselectData"
                    :height="isFullscreen ? '72vh' : '50vh'"
                >
                    <template slot="action" slot-scope="scope">
                        <i
                            class="el-icon-circle-close"
                            @click="cancelButton(scope.row)"
                        ></i>
                    </template>
                </Table>
                <div class="confirm-btn">
                    <el-button type="primary" size="small" @click="isConfirm" v-permission="['version:manager:association']"
                        >确定</el-button
                    >
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { equipment } from "@/api/factuer";
import { softwareVersions } from "@/api/file";
import { removeNullUndefined } from "@/utils/index.js";

import { handleConfirm } from "@/utils/messageBox";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "./table.vue";

export default {
    components: { Pagination, Table },
    props: {
        isFullscreen: {
            type: Boolean,
            default: true,
        },
        equipVisible: {
            type: Boolean,
            default: false,
        },
        versionId: {
            type: String,
            default: "",
        },
    },
    filters: {
        filterVersion(item) {
            // 转换后的二维数组
            if (
                item.equipSoftwareVersions &&
                item.equipSoftwareVersions.length > 0
            ) {
                let arrayTwo = Object.values(
                    item.equipSoftwareVersions.reduce((res, item) => {
                        res[item.partType]
                            ? res[item.partType].push(item)
                            : (res[item.partType] = [item]);
                        return res;
                    }, {})
                );
                let jsons = "";
                arrayTwo.map((item, index) => {
                    jsons += "<div>" + item[0].partTypeName + "：";
                    item.filter((qq, inx) => {
                        jsons +=
                            item.length > 1
                                ? `<span class="addrId">${qq.addrId}</span> ${qq.version}；`
                                : qq.version;
                    });
                    jsons += "</div>";
                });
                return jsons;
            } else {
                return "";
            }
        },
    },
    watch: {
        equipVisible: {
            handler(val) {
                if (val) {
                    this.getDetailList();
                    this.getConnectEquipList();
                }
            },
            immediate: true,
        },
    },
    data() {
        return {
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                codes: "",
            },
            unselectData: [],
            equipTotal: 0,
            unselectTableHeader: [
                { slot: "action", label: "操作", width: "50" },
                {
                    label: "ID",
                    prop: "id",
                    tooltip: true,
                },
                { label: "设备编码", prop: "code", width: "192" },
            ],
            equipTableData: [],
            equipTableHeader: [
                {
                    type: "selection",
                    width: "40",
                    label: "多选",
                    fixed: "left",
                },
                {
                    label: "ID",
                    prop: "id",
                    width: "120",
                    tooltip: true,
                },
                { slot: "codes", label: "设备编码", width: "220" },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                    width: "78",
                },
                { slot: "softVersion", label: "版本" },
            ],
            equipTotal: 0,
            handleListLoading: false,
        };
    },

    methods: {
        //限制输入特殊字符
        keyUp(e) {
            let str = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            e.target.value = str;
            this.searchForm.codes = str;
        },
        // 只能输入汉字、英文、数字
        keyInput(e) {
            let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
            e.target.value = str;
            this.searchForm.codes = str;
        },
        handleUnselectData(e) {
            this.unselectData = e;
        },
       
        cancelButton(row) {
            this.unselectData = this.unselectData.filter(
                (item) => item.id != row.id
            );
        },
        getDetailList() {
            this.handleListLoading = true;
            let param = { ...this.searchForm };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            equipment(
                "/version/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    this.equipTableData = res.data;
                    this.equipTotal = +res.total;
                })
                .finally(() => {
                    this.handleListLoading = false;
                });
        },
        getConnectEquipList() {
            softwareVersions(`/equip/list/${this.versionId}`, "post").then(
                (res) => {
                    this.unselectData = res.data? res.data:[];
                }
            );
        },
        doUpdateSearch() {
            this.unselectData = [];
            this.equipTableData = [];
            this.equipTotal = 0;
            this.getDetailList();
            this.getConnectEquipList();
        },
        isConfirm() {
            if (this.equipTableData.length == 0) {
                this.$message.error("暂无可设备，请重新筛选！");
                return;
            } 

            handleConfirm(`确定要${this.unselectData.length == 0 ? '重置' :'关联'}设备吗？`, "warning", "提示")
                .then((res) => {
                    this.doHandleConnect();
                })
                .catch((err) => {});
        },
        doHandleConnect() {
            let equipIds = this.unselectData.map((item) => {
                return item.id;
            });
            softwareVersions(
                `/equip/save`,
                "post",
                {
                    softwareVersionId: this.versionId,
                    equipIds: equipIds.join(","),
                },
                2
            ).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                }
            });
        },

        resetDialogSearch() {
            this.searchForm.codes = "";
        },
    },
};
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
.codes {
    @include flexLayout(center, center);

    img {
        width: 20px;
        margin-left: 10px;
    }

    .isAllow {
        color: red;
    }
}
.link-text {
    margin: 10px 0;
    font-weight: bold;
}
.el-icon-circle-close {
    font-size: 18px;
    color: #f56c6c;
}
.pagination-container {
    padding: 16px;
}
.confirm-btn {
    text-align: right;
    margin: 10px 0;
}
</style>
